package viper.receive;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import viper.main.StateManager;

/**
 * @author Kevin Sin
 * 
 * Revision number: 1
 * Date created: 1/20/10
 * Date of Last Back-up on SVN: none
 * 
 * <p>Like UDPSender, this is a singleton class that provides
 * the basic receive function.  It will continuously listen for packets
 * and pass them off to the right handler.
 */
public class UDPReceiver {
	
	//singleton structure
	public final static UDPReceiver INSTANCE = new UDPReceiver();
	private UDPReceiver(){
		try {
			datagramSocket = new DatagramSocket(StateManager.VIPER_PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	private boolean listening; //true if listening for UDP packets
	
	private DatagramSocket datagramSocket; //UDP socket
	
	//max UDP packet size in bytes
	public final static int MAX_PACKET_SIZE = 50; 
	
	/**
	 * This method makes UDPReceiver start listening for packets.
	 */
	public void startListening() {
		listening = true;
		while(listening)
		{
		    try {
		    	DatagramPacket packet = 
		    		new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
		    	datagramSocket.receive(packet);
		    	byte[] data = packet.getData();
		    	System.out.println(data[0] + " " + data[1] + " " + data[2] + " " + data[3]);
		    } catch (SocketException e) {
		    	e.printStackTrace();
		    } 
		    catch (IOException e) {
		    	e.printStackTrace();
		    }
		}
	}
	
	/**
	 * This method makes UDPReceiver stop listening.
	 */
	public void stopListening() {
		listening = false;
	}
}
